/**
 * 
 */
package org.o14x.alpha.ui.commands;

import java.io.File;
import java.util.Iterator;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.commands.ICommandService;
import org.o14x.alpha.ui.controller.UIController;
import org.o14x.alpha.ui.views.folder.FolderView;
import org.o14x.alpha.ui.views.foldertree.FolderTreeView;

/**
 * Copy command
 * 
 * @author Olivier DANGREAUX
 */
public class CopyCommand extends AbstractHandler {
	private UIController uiController;

	@SuppressWarnings("unchecked")
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		// gets the selection
		IStructuredSelection selection = null;
		if (PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart() instanceof FolderView) {
			selection = (IStructuredSelection) uiController.getDomain().getCurrentExplorerTab().getFolderView().getTableViewer().getSelection();
		} else if (PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart() instanceof FolderTreeView) {
			selection = (IStructuredSelection) uiController.getDomain().getCurrentExplorerTab().getExplorerTreeViewer().getSelection();
		}		
		
		// converts selected files to path array
		String[] selectedPaths = new String[selection.size()];
		int i = 0;
		for (Iterator iterator = selection.iterator(); iterator.hasNext();) {
			File selectedFile = (File) iterator.next();
			selectedPaths[i] = selectedFile.getAbsolutePath();
			i++;
		}

		// sets the content of the clipboard
		Clipboard cb = new Clipboard(PlatformUI.getWorkbench().getDisplay());
		FileTransfer fileTransfer = FileTransfer.getInstance();
		cb.setContents(new Object[] { selectedPaths }, new Transfer[] { fileTransfer });
		cb.dispose();
		
		// mark clipboard as cut
		uiController.getDomain().getClipboard().setCut(false);
		
		// refresh paste commad status
		ICommandService service = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);
		service.refreshElements("org.o14x.alpha.ui.commands.PasteCommand", null); //$NON-NLS-1$

		return null;
	}

	/**
	 * Returns the value of uiController.
	 *
	 * @return The value of uiController.
	 */
	public UIController getUiController() {
		return uiController;
	}

	/**
	 * Sets the value of uiController.
	 *
	 * @param uiController The value of uiController to set.
	 */
	public void setUiController(UIController uiController) {
		this.uiController = uiController;
	}
}
